"""
@Time ： 2025/9/18 10:41
@Auth ： zh
@File ：student_queries.py
"""
"""学生表查询相关业务逻辑"""
from db_utils import MySQLConnector
from config import DB_CONFIG


def query_students(condition=None):
    """查询student表数据"""
    # 使用上下文管理器自动管理连接
    with MySQLConnector(**DB_CONFIG) as connector:
        if connector.connection:
            query = "SELECT * FROM student"
            if condition:
                query += f" WHERE {condition}"
            return connector.execute_query(query)


def get_all_students():
    """获取所有学生信息"""
    return query_students()


def get_adult_students(age=18):
    """获取成年学生信息（默认18岁及以上）"""
    return query_students(f"age >= {age}")


def get_student_by_name(name):
    """根据姓名查询学生"""
    return query_students(f"name = '{name}'")

def add_student(name, gender, score, age):
    """添加学生信息
    :param name: 姓名（varchar）
    :param gender: 性别（varchar）
    :param score: 分数（数值）
    :param age: 年龄（数值）
    :return: 受影响的行数
    """
    with MySQLConnector(**DB_CONFIG) as connector:
        if connector.connection:
            query = """
                INSERT INTO student (name, gender, score, age)
                VALUES (%s, %s, %s, %s)
            """
            # 使用正确的方法名，例如 execute 或 update
            return connector.execute(query, (name, gender, score, age))
